package cn.lj.service.impl;


import cn.lj.common.enums.UserTypeEnum;
import cn.lj.common.handler.BusinessException;
import cn.lj.common.response.Result;
import cn.lj.common.response.ResultCode;
import cn.lj.entity.User;
import cn.lj.mapper.UserMapper;
import cn.lj.service.UserService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 李津
 * @since 2021-04-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     *  添加用户
     * @param user
     */
    @Override
    public void addUser(User user) {
        //判断是否增加重复的用户-用户名和登录名不能相同
        String userName = user.getUserName();
        String loginName = user.getLoginName();

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",userName);
        wrapper.eq("login_name",loginName);

        Integer count = this.baseMapper.selectCount(wrapper);
        if (count!=0){
            //账号已经存在
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }

        //使用enum类默认添加的用户是普通用户1
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());

        //使用spring security自带密码加密策略
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        this.baseMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
        //判断是否增加重复的用户-用户名和登录名不能相同
        String userName = user.getUserName();
        String loginName = user.getLoginName();

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",userName);
        wrapper.eq("login_name",loginName);

        Integer count = this.baseMapper.selectCount(wrapper);
        if (count!=0){
            //账号已经存在
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }

        //使用enum类默认添加的用户是普通用户1
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());

        //使用spring security自带密码加密策略
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        this.baseMapper.updateById(user);
    }

    @Override
    public User findByLoginName(String loginName) {
        return this.baseMapper.findByLoginName(loginName);
    }


    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> users) throws IOException {
        //----- 写入excel文件
        String exportFileName = "UserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(users);
    }


    /**
     * 删除单表用户
     * @param id
     * @return
     */
    @Override
    public Result delUser(Long id) {
        this.baseMapper.deleteById(id);
        return Result.ok();
    }


}
